<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
    //上传图片
    public function image(Request $request){
        $img = $request->post('image');
        if($img){
            $b = mb_strpos($img,'image/') + mb_strlen('image/');
            $e = mb_strpos($img,';base64') - $b;
            $format = mb_substr($img,$b,$e);
            $base_img = str_replace('data:image/'.$format.';base64,','', $img);
            //  设置文件路径和文件前缀名称


            $file_path = date("Y-m-d",time())."/";
            $path = base_path('public/uploads')."/".$file_path;
            if(!file_exists($path)){
                @mkdir($path);
            }
            $output_file = md5(time().rand(100,999)).'.'.$format;
            $path = $path.$output_file;
            //  创建将数据流文件写入我们创建的文件内容中
//            $ifp = fopen( $path, "wb" );
//            fwrite( $ifp, base64_decode( $base_img) );
//            fclose( $ifp );
            // 第二种方式
             $res = file_put_contents($path, base64_decode($base_img));
            // 输出文件
            $disk = Storage::disk('image');

            $path= $file_path.$output_file;
            if($res){
                return response()->json([
                    "code" => 1,
                    "msg" => "上传成功！",
                    "data" =>['path'=>$disk->url($path)]
                ]);
            }else{
                return response()->json([
                    "code" => 0,
                    "msg" => "上传失败！",
                    "data" =>''
                ]);
            }
        }

        if ($request->hasFile('image') && $request->file('image')->isValid()) {
            $disk = Storage::disk('image');
            $photo = $request->file('image');
            $realPath = $photo->getRealPath();//临时文件路径
            $name = hash_file('md5',$realPath);
            $time = date('Y-m-d');
            $fileName = $time.'/'.$name.'.'.$photo->getClientOriginalExtension();
            $bool = $disk->put($fileName, file_get_contents($realPath));
            // 判断是否上传成功
            if ($bool) {
                return $this->writeJson(0,['path'=>$disk->url($fileName)]);
            }
        }
        return $this->writeJson(1,null,'上传错误');
    }

    //上传文件
    public function file(Request $request){
        if ($request->hasFile('file') && $request->file('file')->isValid()) {
            $disk = Storage::disk('file');
            $photo = $request->file('file');
            $realPath = $photo->getRealPath();//临时文件路径
            $name = $photo->getClientOriginalName();
            $time = date('Y-m-d');
            $fileName = $time.'/'.$name;
            $bool = $disk->put($fileName, file_get_contents($realPath));
            // 判断是否上传成功
            if ($bool) {
                return $this->writeJson(0,['path'=>$disk->url($fileName)]);
            }
        }
        return $this->writeJson(1,null,'上传错误');
    }

}
